package spring.cloud.tasks.api.service.impl;

import com.google.gson.Gson;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import spring.cloud.tasks.api.database.entity.NameSpaceZooKeeperClusterMappingDto;
import spring.cloud.tasks.api.database.entity.ZooKeeperClusterDto;
import spring.cloud.tasks.api.database.service.NameSpaceZooKeeperClusterMappingDtoService;
import spring.cloud.tasks.api.database.service.TaskConfigurationDtoService;
import spring.cloud.tasks.api.database.service.ZooKeeperClusterDtoService;
import spring.cloud.tasks.api.domain.NamespaceZooKeeperClusterMapping;
import spring.cloud.tasks.api.domain.ZooKeeperCluster;
import spring.cloud.tasks.api.service.NameSpaceZooKeeperClusterMappingService;
import spring.cloud.tasks.api.service.TaskService;
import spring.cloud.tasks.api.service.ZooKeeperService;
import spring.cloud.tasks.api.zookeeper.ZooKeeper;
import spring.cloud.tasks.api.zookeeper.ZooKeeperRepository;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Setter
@Getter
public class NamespaceZooKeeperClusterMappingServiceImpl implements NameSpaceZooKeeperClusterMappingService {

    public static final String MOVE_NAMESPACE_BATCH_STATUS = "MOVE_NAMESPACE_BATCH_STATUS";
    @Resource
    private ZooKeeperClusterDtoService zooKeeperClusterDtoService;
    @Resource
    private NameSpaceZooKeeperClusterMappingDtoService nameSpaceZooKeeperClusterMappingDtoService;
    @Resource
    private ZooKeeperRepository zooKeeperRepository;
    @Resource
    private TaskConfigurationDtoService taskConfigurationDtoService;
    @Resource
    private TaskService taskService;
    @Resource
    private ZooKeeperService zooKeeperService;

    private Gson gson = new Gson();


    @Override
    public List<NamespaceZooKeeperClusterMapping> getNamespaceZooKeeperClusterMappingList() throws RuntimeException {
        List<NamespaceZooKeeperClusterMapping> list = new ArrayList<NamespaceZooKeeperClusterMapping>();
        List<NameSpaceZooKeeperClusterMappingDto> dtoList = nameSpaceZooKeeperClusterMappingDtoService.getNameSpaceZooKeeperClusterMappingDtoList();
        if (dtoList != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (NameSpaceZooKeeperClusterMappingDto dto : dtoList) {
                try {
                    if (dto.getIsDeleted() == 0) {
                        NamespaceZooKeeperClusterMapping vo = new NamespaceZooKeeperClusterMapping();
                        vo.setCreatedBy(dto.getCreatedBy());
                        vo.setCreateDateTime(sdf.format(dto.getCreateDateTime()));
                        vo.setLastUpdatedBy(dto.getLastUpdatedBy());
                        vo.setLastUpdateDateTime(sdf.format(dto.getLastUpdateDateTime()));
                        //
                        vo.setNamespace(dto.getNameSpace());
                        vo.setZooKeeperClusterKey(dto.getZooKeeperClusterKey());

                        list.add(vo);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return list;
    }

    @Override
    public void initNameSpaceZooKeeperClusterMapping(String createdBy) throws RuntimeException {
        try {
            List<ZooKeeperClusterDto> zooKeeperClusterDtoList = zooKeeperClusterDtoService.getZooKeeperClusterInfoList();
            if (zooKeeperClusterDtoList != null) {
                for (ZooKeeperClusterDto zooKeeperClusterDto : zooKeeperClusterDtoList) {
                    String zooKeeperClusterKey = zooKeeperClusterDto.getZooKeeperClusterKey();
                    String connectString = zooKeeperClusterDto.getConnectString();
                    CuratorFramework curatorFramework = null;
                    ZooKeeper zooKeeper = zooKeeperService.connectOnly(connectString, null);
                    if (zooKeeper != null) {
                        curatorFramework = zooKeeper.getCuratorFramework();
                    }
                    if (curatorFramework != null) { // not offline
                        updateNamespaceZooKeeperClusterMapping(createdBy, zooKeeperClusterKey, curatorFramework);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    private void updateNamespaceZooKeeperClusterMapping(String createdBy, String zooKeeperClusterKey, CuratorFramework curatorFramework) throws Exception {
        try {
            List<String> nameSpaceList = curatorFramework.getChildren().forPath("/");
            if (nameSpaceList != null) {
                for (String nameSpace : nameSpaceList) {
                    if (zooKeeperService.nameSpaceIsCorrect(nameSpace, curatorFramework)) {
                        nameSpaceZooKeeperClusterMappingDtoService.insert(nameSpace, zooKeeperClusterKey, createdBy);
                    }
                }
            }
        } finally {
            curatorFramework.close();
        }
    }

    @Override
    public List<String> getOnlineZooKeeperClusterKeyList() throws RuntimeException {
        List<String> zooKeeperClusterKeyList = new ArrayList<>();
        List<ZooKeeperCluster> zooKeeperClusterList = zooKeeperService.getZooKeeperClusterList();
        if (zooKeeperClusterList != null) {
            Iterator<ZooKeeperCluster> iterator = zooKeeperClusterList.iterator();
            while (iterator.hasNext()) {
                ZooKeeperCluster next = iterator.next();
                if (!next.isOffline()) {
                    zooKeeperClusterKeyList.add(next.getZooKeeperClusterKey());
                }
            }
        }
        return zooKeeperClusterKeyList;
    }


}
